<template lang="pug">
  .CreateCityModal
    Modal(
      v-model="isShowCreateCityModal"
      :title="isCreate ? '新增城市' : '修改城市'"
      class-name="vertical-center-modal"
      width="480"
    )
      Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="100")
        FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'cascader'")
            .areaTree
              Cascader(v-model="formData[item.model]" :data="areaTree" :load-data="loadDataCity" clearable :change-on-select="initView" @on-visible-change="areaVisibleChange" @on-change="areaTreeChange(item.model, $event)" :render-format="areaTreeFormat")
          template(v-if="item.type === 'upload'")
            Row
              Col(span="24")
                Upload(
                  ref="upload"
                  :max-size="10 * 1024"
                  :on-exceeded-size="handleMaxSizeTen"
                  :before-upload="handleBeforeUpload"
                  :on-success="uploadSuccess"
                  accept=".xls, .xlsx"
                  :action="baseUrl + 'api/Treatment/TreatmentAnnexUpload'"
                  :show-upload-list="false"
                )
                  Input(v-model="formData[item.model].name" v-show="false")
                  Button(type="info") 附件上传
              Col(span="24")
                .text-gray-9 仅支持上传10M以内的xlsx文件
              Col(span="24" v-if="file")
                Tag {{file.name}}
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSave()" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import dataApi from '@/api/data.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
export default {
  name: 'CreateCityModal',

  watch: {
  },

  computed: {
  },

  data () {
    return {
      baseUrl: baseUrl,
      isShowCreateCityModal: false,
      // createCityModalTitle: '',
      isCreate: true,      
      parameterID: '',
      formData: {
        id: '',
        // parameterID: '',
        // parameterStatus: '',
        rowVersion: '',
        area: '',
        areaFullID: [],
        areaFullName: '',
        fileAnnex: '',
        fileAnnexName: ''
      },
      formItem: [
        { type: 'cascader', label: '城市：', placeholder: '请选择城市', prop: 'areaFullID', model: 'areaFullID', style: 'ivu-col-span-24' },
        { type: 'upload', label: '附件：', placeholder: '请上传附件', prop: 'fileAnnex', model: 'fileAnnex', style: 'ivu-col-span-24' },
      ],
      rules: {
        areaFullID: [
          { required: true, message: '请选择城市', trigger: 'change', type: 'array' }
        ],
        fileAnnex: [
          { required: true, message: '请上传附件', trigger: 'change' }
        ]
      },
      arrListDown: {
        tempOps: []
      },
      areaTree: [], // 中国所有城市树
      errorData: {
        errorId: '',
        isError: false,
        downLoadUrl: null
      },
      file: null,
      isCanSubmit: true,
      initView: false
    }
  },

  mounted () {
    this.getProvince()
    // this.areaTree = JSON.parse(localStorage.getItem('areaTree')) // 获取中国所有城市树
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    cancel () {
      this.isShowCreateCityModal = false
    },

    show () {
      this.file = null
      this.isCanSubmit = true
      this.isShowCreateCityModal = true
      this.$refs.formData.resetFields()
      Object.keys(this.formData).forEach(key => {
        if (['areaFullID'].indexOf(key) !== -1) {
          this.formData[key] = []
        } else {
          this.formData[key] = ''
        }
      })
      console.log('this.formData: ', this.formData)
    },

    /**
     * 查询所有省
     */
    getProvince () {
      dataApi.getProvince().then(res => {
        this.areaTree = res.data.data.map(item => {
          return {
            ...item,
            label: item.name,
            value: item.id,
            children: [],
            loading: false
          }
        })
      })
    },
    /**
     * 分级查询地区
     */
    loadDataCity (val, callback) {
      console.log('val: ', val)
      val.loading = true
      if (val.levelID === 2) {
        dataApi.getCity({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.id,
              children: [],
              loading: false
            }
          })
          val.loading = false
          callback()
        })
      } else {
        dataApi.getArea({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return { ...item, label: item.name, value: item.id }
          })
          val.loading = false
          callback()
        })
      }
    },

    // 所在地区选择
    areaTreeChange (model, value) {
      this.formData.areaFullID = value
      this.formData.area = value[value.length - 1]
    },

    // 展开收起联级框
    areaVisibleChange (isVisible) {
      console.log('isVisible: ', isVisible)
      if (isVisible) {
        this.initView = true
      } else {
        this.initView = false
      }
    },

    areaTreeFormat (labels, selectedData) {
      // const index = labels.length - 1;
      // const data = selectedData[index] || false;
      // if (data && data.code) {
      //   return labels[index] + '-' + data.code;
      // }
      // return labels[index];
      console.log('labels: ', labels)
      console.log('selectedData: ', selectedData)
      if (labels.length) {
        var str = labels.join('-')
        return str
      } else {
        return this.formData.areaFullName
      }
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },

    // 批量导入-上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.formData.fileAnnex = []
      } else {
        this.errorData.isError = false
        this.file = file
      }
      // this.errorData.isError = false
      // this.file = file
      // console.log('file: ', this.file)
      // return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ',res)
      var fileName = res.Data.Name
      var str = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
      if (res.Success) {
        if (['.xls', '.xlsx'].indexOf(str) !== -1) {
          this.formData.fileAnnex = res.Data.Id
          this.formData.fileAnnexName = res.Data.Name
        } else {
          this.file = null
          this.formData.fileAnnex = []
        }
      }
    },

    // 根据ID获取参数城市
    async getModel (id) {
      console.log('id: ', id)
      let res = await TreatmentApi.getTreatmentParameterCity({ParameterCityId: id})
      console.log('根据ID获取参数城市: ', res)
      if (res.status === 200 && res.data.success) {
        var data = res.data.data
        this.file = {
          name: data.fileAnnexName
        }
        Object.keys(this.formData).forEach(key => {
          if (key === 'areaFullID') {
            var areaFullID = (data[key].toUpperCase()).split(',')
            this.formData.areaFullID = areaFullID.splice(1, areaFullID.length)
            console.log('this.formData.areaFullID: ', this.formData.areaFullID)
          } else {
            this.formData[key] = data[key] + '' && data[key] + '' !== 'null' ? data[key] + '' : ''
          }
        })
      } else {
      }
    },

    // 保存
    async handleSave () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          var params = {ParameterID: this.parameterID}
          TreatmentApi.saveTreatmentParameterCitys({...this.formData, ...params}).then(res => {
            console.log('保存: ', res)
            if (res.status === 200 && res.data.success) {
              this.$Message.success(res.data.message)
              this.cancel()
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
          this.cancel()
        } else {
          this.isCanSubmit = true
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
